package cn.tm.liu.mvc.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author Marvin.L
 * @description
 * @date 2022.03.30 11.17
 */
@Slf4j
@Component
public class ResponseInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            log.info("请求进入拦截:{}", request.getRequestURI());
            addCookie(response, new Cookie("JSESSIONID", request.getSession().getId()));
            addCookie(response, new Cookie("Main", "TestValue"));
            response.setHeader("Session", request.getSession().getId());
            if (request.getRequestURI().equals("/error")) {
                request.getRequestDispatcher("/404").forward(request, response);
                return false;
            }
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(ResponseResult.class)) {
                ResponseResult responseResult = clazz.getAnnotation(ResponseResult.class);
                if (responseResult.ignoreMethods().length > 0) {
                    for (String methodName : responseResult.ignoreMethods()) {
                        if (methodName.equals(method.getName()))
                            return true;
                    }
                }
                request.setAttribute(ResponseResult.RESPONSE_RESULT_ANN, clazz.getAnnotation(ResponseResult.class));
            } else if (method.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute(ResponseResult.RESPONSE_RESULT_ANN, method.getAnnotation(ResponseResult.class));
            }
            request.setAttribute(ResponseResult.REQUEST_BEGIN, new Date());
        } else {
            log.warn("未找到适配:{}", request.getRequestURI());
        }
        return true;
    }

    public void addCookie(HttpServletResponse response, Cookie cookie) {
        // Cookie cookie = new Cookie("name_test","value_test");//创建新cookie
        cookie.setMaxAge(30 * 60);// 设置存在时间为5分钟
        cookie.setPath("/");//设置作用域
        response.addCookie(cookie);//将cookie添加到response的cookie数组中返回给客户端
    }
}
